/**
 * 15-600: Java and J2EE
 * Instructor: Jeff Eppinger
 * Done By:	Mohammad al Khani
 * Date Dec 10, 2011
 */

package controller;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import model.Model;
import model.UserDAO;

import org.mybeans.form.FormBeanException;
import org.mybeans.form.FormBeanFactory;

import dataBeans.User;
import exceptions.MyWebsiteException;
import formBean.LoginForm;

public class LoginAction extends Action{

	private FormBeanFactory<LoginForm> formBeanFactory = FormBeanFactory.getInstance(LoginForm.class);
	private UserDAO userDAO;

	public LoginAction(Model model) {
		userDAO = model.getUserDAO();
	}

	public String getName(){ 
		return "login.do"; 
	}
    
    public String perform(HttpServletRequest request) {
        List<String> errors = new ArrayList<String>();
        request.setAttribute("errors",errors);
        
        try {
	    	LoginForm form = formBeanFactory.create(request);
	        request.setAttribute("form",form);
	        
	        if (!form.isPresent()) {
	            return "login.jsp";
	        }

	        errors.addAll(form.getValidationErrors());
	        if (errors.size() != 0) {
	            return "login.jsp";
	        }

	        User user = userDAO.login(form.getEmail(), form.getPassword());
	        HttpSession session = request.getSession();
	        session.setAttribute("user",user);
	        String redirectTo = (String) session.getAttribute("redirectTo");
	        if (redirectTo != null){ 
	        	return redirectTo;
	        }
	        
			String webapp = request.getContextPath();
			return webapp + "/manage.do";
        } 
        catch(MyWebsiteException e){
        	errors.add(e.toString());
        	return "login.jsp";
        } catch (FormBeanException e) {
        	errors.add(e.getMessage());
        	return "error.jsp";
        }catch (Exception e) {
        	errors.add(e.getMessage());
        	return "error.jsp";
        }
    }
}
